package com.yuye.cloud.common.config;

import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.*;

/**
 * 线程池 的初始化
 * 单例 / 获取cpu 核数 然后初始化 之后使用的时候 就是 直接单例获取
 * IO 密集型
 * @author xgf
 */
@Setter
@Getter
public class DefaultThreadPoolConfig {
	private volatile  ExecutorService threadPool;
	int cpuCoreNum = Runtime.getRuntime().availableProcessors();
	
	
	private DefaultThreadPoolConfig() {
		
	}
	
	public ExecutorService getInstance() {
		CopyOnWriteArrayList<Object> copyOnWriteArrayList = new CopyOnWriteArrayList<>();
		
		if(threadPool == null) {
			synchronized (DefaultThreadPoolConfig.class) {
				if(threadPool == null) {
					threadPool = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() + 1, 
							Runtime.getRuntime().availableProcessors() * 2
							, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(500), 
							new ThreadFactory() {
								
								@Override
								public Thread newThread(Runnable r) {
									Thread thread = new Thread(r, "xxx-thread-pool");
									thread.setDaemon(true);
									return thread;
								}
							},
							new ThreadPoolExecutor.CallerRunsPolicy());
				}
			}
		}
		
		
		return threadPool;
		
	}
	
}
